package jsu.lipengcheng.trafficnet.Ai;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.ChatMessageDeserializer;
import dev.langchain4j.data.message.ChatMessageSerializer;
import dev.langchain4j.store.memory.chat.ChatMemoryStore;
import jsu.lipengcheng.trafficnet.common.BeanThread;
import jsu.lipengcheng.trafficnet.mapper.AidateMapper;
import jsu.lipengcheng.trafficnet.pojo.Aibate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Component
public class SqlChatMemoryStores implements ChatMemoryStore {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private AidateMapper aidateMapper;

    @Override
    public List<ChatMessage> getMessages(Object memoryid) {
        String json = stringRedisTemplate.opsForValue().get(memoryid.toString());
        if (json == null) {
            Aibate aibate = aidateMapper.selectOne(new QueryWrapper<Aibate>().eq("memory_id", memoryid.toString()));
            if (aibate == null) {
                return Collections.emptyList();
            }
            List<ChatMessage> list = ChatMessageDeserializer.messagesFromJson(aibate.getText());
            stringRedisTemplate.opsForValue().set(memoryid.toString(), aibate.getText(), 1, TimeUnit.DAYS);
            return list;
        }
        List<ChatMessage> list = ChatMessageDeserializer.messagesFromJson(json);
        return list;
    }

    @Override
    public void updateMessages(Object memoryid, List<ChatMessage> list) {
        String string = UUID.randomUUID().toString();
        String json = ChatMessageSerializer.messagesToJson(list);
        Aibate aibate=new Aibate(string,memoryid.toString(),json);
        Aibate result = aidateMapper.selectOne(new QueryWrapper<Aibate>().eq("memory_id", memoryid.toString()));
        if (result==null){
            aidateMapper.insert(aibate);
            stringRedisTemplate.opsForValue().set(memoryid.toString(),json,1, TimeUnit.DAYS);
            return;
        }
        aidateMapper.update(aibate,new UpdateWrapper<Aibate>().set("text",json).eq("memory_id", memoryid.toString()));
        stringRedisTemplate.opsForValue().set(memoryid.toString(),json,1, TimeUnit.DAYS);
    }

    @Override
    public void deleteMessages(Object memoryid) {
        aidateMapper.delete(new QueryWrapper<Aibate>().eq("memory_id", memoryid.toString()));
        stringRedisTemplate.delete(memoryid.toString());
    }
}
